<?php

/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Modules\Blog\Service;


use App\Models\Common\Category;
use App\Models\Common\FailedJob;
use App\Models\Common\Region;
use App\Models\System\Config;
use App\Models\System\File;
use App\Services\Service;
use Illuminate\Http\Request;

class CommonService
{

    use Service;

    /**
     * 获取用户信息
     *
     * @return int
     */
    public function UserCommonService()
    {
        try {
            return \JWTAuth::parseToken()->authenticate();
        } catch (\Exception $exception) {
            return 0;
        }
    }

    /**
     * 获取验证码
     *
     * @param  Request  $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function CodeEmailCommonService($request)
    {
        $error     = $this->getErrorCode();
        $static    = $request->input('static', 'login');
        $email     = $request->input('email');
        $validator = $this->getBlogValidator()->BlogEmailCodeValidator($request);//验证字段
        if ($validator->first()) {
            return message($validator->first());
        }
        $codeKey = 'blog:'.$static.':code:code'.$email;
        $redis   = $this->getRedisLibs();
        if (!$redis->exists($codeKey)) {
            $redis->incr($codeKey);                                      //增加redis 值
            $redis->expire($codeKey, (int) config('blog_page.CODE_DAY'));//设置过期时间
        } else {
            if ($redis->get($codeKey) >= (int) config('blog_page.CODE_STRIP')) {
                return message('您今天的验证码次数以用完，重置时间剩余：'.secToTime($redis->ttl($codeKey), 'd'));
            }//发送短信次数从配置读取
            else {
                $redis->incr($codeKey);
            }
        }//增加redis 值
        $key               = 'blog:'.$static.':code:'.$email;
        $code              = GetRandStr();//验证码
        $data[ 'name' ]    = '发送验证码';
        $data[ 'email' ]   = $email;
        $data[ 'content' ] = "您的验证码是 $code 验证码10分钟内有效";
        $data[ 'code' ]    = $code;
        $data[ 'id' ]      = false;
        $json              = json_encode($data);                         //转json 字符串
        $redis->set($key, $json, (int) config('blog_page.CODE_SECONDS'));//验证码期时间
        FailedJob::CreateModel(['key' => 'queues:default:reserved', 'content' => $json]);
        $success[ '验证码' ] = $code;
        $success[ '邮箱号' ] = $email;
        $success[ '内容' ]  = $data[ 'content' ];
        errorStorage('blogCode', $success, '发送验证码成功', 'success', '发送验证码');
        return data(null, $error::message(201));
    }

    /**
     * 获取公共数据
     *
     * @param  Request  $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function PublicDataCommonService($request)
    {
        $data = [];
        switch ($request->input('status')) {
            case 'region':
                $select = ['id', 'name', 'parent_id', 'type'];
                $where  = function ($query) use ($request) {
                    $query->where($request->input('get'), $request->input('key') ?: 100000);
                };
                $data   = Region::GetModel($where, [], $select);
                break;
            case 'config':
                $select = [
                    'name',
                    'url',
                    'title',
                    'word',
                    'riptive',
                    'record',
                    'info',
                    'company',
                    'qq',
                    'box',
                    'phone',
                    'fixed',
                    'fax',
                    'image',
                ];
                $with   = [
                    'file' => function ($query) {
                        $query->select('id', 'url');
                    },
                ];
                $data   = Config::FindModel(['status' => 2], $with, $select);
                break;
            case 'category':
                $select = ['id', 'parent_id', 'name', 'sort_order', 'is_show', 'status'];
                $where  = function ($query) use ($request) {
                    $query->where('status', 1);
                    $query->where('is_show', $request->input('is_show', 1));
                    $query->where('static', $request->input('static'));
                    $query->where('parent_id', $request->input('parent_id', 0));
                };
                $data   = Category::GetModel($where, [], $select);
                break;
            case 'file':
                $user   = $this->UserCommonService();
                $select = ['id', 'name', 'url',];
                $where  = function ($query) use ($request, $user) {
                    $query->where('status', 1);
                    if ($request->input('user', 0) == 0) {
                        $name = [0, $user->id];
                    } else {
                        $name = [$user->id];
                    }
                    $query->whereIn('user_id', $name);
                    $query->where('is_show', $request->input('is_show', 2));
                };
                $data   = File::PaginateModel($where, [], $select);
                break;
            default:
                break;
        }
        return data($data);
    }

}
